
//
//  FZPictureView.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/3/31.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit
import SDWebImage
//配图view
class FZPictureView: UICollectionView , UICollectionViewDataSource,UICollectionViewDelegate,SDPhotoBrowserDelegate{
    
    fileprivate let margin = 10
    fileprivate lazy var dataArray : [FZPictureInfo] = [FZPictureInfo]()
    //图片源
    var statusPictureModel : [FZPictureInfo]? {
        
        didSet {
            if let picCount = statusPictureModel?.count{
                
                calculation(picCount: picCount , imgArr: statusPictureModel!)
                
                if statusPictureModel != nil {
                    dataArray = statusPictureModel!
                }
            }
            self.reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: layout)
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        layout.itemSize = CGSize(width:itemWidth, height: itemWidth)
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        self.register(FZHomeCollectionCell.self, forCellWithReuseIdentifier: homeCollectionCell)
        
        self.dataSource = self
        self.delegate = self
    }
    
    
    func calculation(picCount : Int , imgArr : [FZPictureInfo]) {
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if picCount == 0 {
            self.snp.updateConstraints { (make) in
                make.size.equalTo(CGSize(width: 0, height: 0))
            }
            return
        }
        
        if picCount == 1 {
            
         let imgUrlStr = imgArr.first?.thumbnail_pic
         let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imgUrlStr)
            
            if let img = image {
                
                self.snp.updateConstraints { (make) in
                    
                    make.size.equalTo(img.size)
                }
                
                 layout.itemSize = img.size
            }else{
                self.snp.updateConstraints { (make) in
                    
                    make.size.equalTo(CGSize(width: itemWidth, height: itemWidth))
                }
                
                layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
 
            }
            return
        }
        
        
        //边缘间距
        //图片间距
        //列数
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        let col = picCount > 3 ? 3 : picCount
        //行数
        let row = (picCount - 1)/3 + 1
       
        let collectionWidth = CGFloat(col) * itemWidth + CGFloat(col - 1) * itemDistance
        
        let collectionHeight = CGFloat(row) * itemWidth + CGFloat(row - 1) * itemDistance
        
        self.snp.updateConstraints { (make) in
            
            make.size.equalTo(CGSize(width: collectionWidth, height: collectionHeight))
        }
        
}
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
   
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
        //        photoBrowser.delegate = self;
        //        photoBrowser.currentImageIndex = indexPath.item;
        //        photoBrowser.imageCount = self.modelsArray.count;
        //        photoBrowser.sourceImagesContainerView = self.collectionView;
        //
        //        [photoBrowser show];
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = dataArray.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    
    // 返回临时占位图片（即原来的小图）
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! FZHomeCollectionCell
        
        return cell.imgView.image
    }
    
    //    - (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
    //    {
    //    // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
    //    SDCollectionViewDemoCell *cell = (SDCollectionViewDemoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    //
    //    return cell.imageView.image;
    //
    //    }
    
    
    // 返回高质量图片的url
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = dataArray[index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
    }
    
    
    //    - (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
    //    {
    //    NSString *urlStr = [[self.modelsArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    //    return [NSURL URLWithString:urlStr];
    //    }
    

    

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        print(dataArray.count)
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homeCollectionCell, for: indexPath) as! FZHomeCollectionCell
        
        cell.imgUrlStr = dataArray[indexPath.item]
        
        return cell
    }
}











